package com.jhgsys.internal.sypq.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.*;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jhgsys.internal.common.entity.FebsConstant;
import com.jhgsys.internal.common.entity.QueryRequest;
import com.jhgsys.internal.common.utils.DateUtil;
import com.jhgsys.internal.dict.service.IDictService;
import com.jhgsys.internal.sypq.entity.*;
import com.jhgsys.internal.sypq.mapper.*;
import com.jhgsys.internal.sypq.service.*;
import com.jhgsys.internal.system.entity.User;
import com.jhgsys.internal.system.service.IUserService;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

import static org.apache.shiro.SecurityUtils.getSubject;

/**
 * 项目设置 Service实现
 *
 * @author ganjun
 * @date 2024-11-12 10:58:48
 */
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class SypqProjectServiceImpl extends ServiceImpl<SypqProjectMapper, SypqProject> implements ISypqProjectService {
    @Autowired
    IProjectManagerService projectManagerService;
    @Autowired
    IWorkflowRecordService workflowRecordService;
    @Autowired
    ModelShipMapper modelShipMapper;
    @Autowired
    ModelOarsMapper modelOarsMapper;
    @Resource
    private ModelAttachMapper modelAttachMapper;
    @Autowired
    TaskMapper  taskMapper;
    @Autowired
    ITaskShipService  taskShipService;
    @Autowired
    ITaskOarsService  taskOarsService;
    @Autowired
    ITaskAttachService  taskAttachService;
    @Resource
    private IDictService dictService;
    @Autowired
    private INoticeService noticeService;

    @Autowired
    private IUserService userService;

    /**
     * 查询（分页）
     *
     * @param request     QueryRequest
     * @param sypqProject sypqProject
     * @return IPage<SypqProject>
     * @author ganjun
     * @date 2024-11-12 10:58:48
     */
    @Override
    public IPage<SypqProjectDto> findSypqProjectPage(QueryRequest request, SypqProjectDto sypqProject,String userid) {
        // TODO 设置查询条件
        Page<SypqProject> page = new Page<>(request.getPageNum(), request.getPageSize());
        return this.baseMapper.getProjectDetailPage(page, sypqProject,userid);

    }

    /**
     * 查询（所有）
     *
     * @param sypqProject sypqProject
     * @return List<SypqProject>
     * @author ganjun
     * @date 2024-11-12 10:58:48
     */
    public List<SypqProject> findSypqProjectList(SypqProject sypqProject) {
        LambdaQueryWrapper<SypqProject> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SypqProject::getDeletedFlg, 0);
        if(StringUtils.isNotEmpty(sypqProject.getProjectCode())){
            queryWrapper.eq(SypqProject::getProjectCode, sypqProject.getProjectCode());
        }
       if(StringUtils.isNotEmpty(sypqProject.getProjectName())){
           queryWrapper.eq(SypqProject::getProjectName, sypqProject.getProjectName());
       }
        if(StringUtils.isNotEmpty(sypqProject.getAuditorid())){
            queryWrapper.eq(SypqProject::getAuditorid, sypqProject.getAuditorid());
        }
        List<SypqProject>  list=this.baseMapper.selectList(queryWrapper);
        return list;
    }

    @Override
    public List<SypqProjectDto> findSypqProjectList(SypqProjectDto sypqProjectDto,String userid) {
        List<SypqProjectDto> list = this.baseMapper.getProjectDetail(sypqProjectDto,userid);
        for (SypqProjectDto dto : list) {
            if (org.apache.commons.lang3.StringUtils.isNotBlank(dto.getFileinfo())) {
                dto.setFileList(JSON.parseArray(dto.getFileinfo()));
            }
        }
        return list;
    }

    /**
     * 根据ID查询
     *
     * @param id
     * @return SypqProject
     * @author ganjun
     * @date 2024-11-12 10:58:48
     */
    @Override
    public SypqProject findSypqProjectById(String id) {
        return this.baseMapper.selectById(id);
    }

    /**
     * 新增
     *
     * @param sypqProject sypqProject
     * @author ganjun
     * @date 2024-11-12 10:58:48
     */
    @Override
    @Transactional
    public boolean createSypqProject(SypqProjectDtoParam dtoParam) {

        SypqProject sypqProject = dtoParam.getSypqProject();
        sypqProject.setStatus(4);
        sypqProject.setDeletedFlg("0");
        if (sypqProject.getApproveStatus() == null) {
            sypqProject.setApproveStatus(1);
        }
        sypqProject.setFileinfo("");
        if (!ObjectUtils.isEmpty(dtoParam.getFileList())) {
            sypqProject.setFileinfo(JSON.toJSONString(dtoParam.getFileList()));
        }
        boolean result = this.save(sypqProject);
        String managerids = dtoParam.getManagerids();
        if (StringUtils.isNotEmpty(managerids)) {
            List<ProjectManager> projectManagerList = new ArrayList<>();
            for (String managerid : managerids.split(",")) {
                ProjectManager projectManager = new ProjectManager();
                projectManager.setProjectCode(sypqProject.getProjectCode());
                projectManager.setUserId(managerid);
                projectManager.setDeletedFlg("0");
                projectManagerList.add(projectManager);
            }
            projectManagerService.saveBatch(projectManagerList);
        }
        if("copy".equals(dtoParam.getType())){
            copymodel(dtoParam.getOldcode() ,sypqProject.getProjectCode());
        }
        return result;
    }

    /**
     * 修改
     *
     * @param sypqProject sypqProject
     * @author ganjun
     * @date 2024-11-12 10:58:48
     */
    @Override
    @Transactional
    public boolean updateSypqProject(SypqProjectDtoParam dtoParam) {
        SypqProject sypqProject = dtoParam.getSypqProject();
        sypqProject.setFileinfo("");
        if (!ObjectUtils.isEmpty(dtoParam.getFileList())) {
            sypqProject.setFileinfo(JSON.toJSONString(dtoParam.getFileList()));
        }
        boolean result = this.updateById(sypqProject);
        projectManagerService.physicallyDeleteByProject(sypqProject.getProjectCode());
        String managerids = dtoParam.getManagerids();
        if (StringUtils.isNotEmpty(managerids)) {
            List<ProjectManager> projectManagerList = new ArrayList<>();
            for (String managerid : managerids.split(",")) {
                ProjectManager projectManager = new ProjectManager();
                projectManager.setProjectCode(sypqProject.getProjectCode());
                projectManager.setUserId(managerid);
                projectManager.setDeletedFlg("0");
                projectManagerList.add(projectManager);
            }
            projectManagerService.saveBatch(projectManagerList);
        }
        return result;
    }


    @Override
    @Transactional
    public boolean commitSypqProject(SypqProjectDtoParam dtoParam) {
        SypqProject sypqProject = dtoParam.getSypqProject();
        sypqProject.setApproveStatus(2);
        if (sypqProject.getCreatedTime() == null) {
            createSypqProject(dtoParam);
        } else {
            updateSypqProject(dtoParam);
         }
        //向审批流表中插入记录
        WorkflowRecord workflowRecord = new WorkflowRecord();
        workflowRecord.setVoucherId(sypqProject.getProjectCode());
        workflowRecord.setVoucherType("5");
        workflowRecord.setStatus(2);
        workflowRecord.setRemark("提交");
        workflowRecord.setDeletedFlg("0");
        boolean res = workflowRecordService.createWorkflowRecord(workflowRecord);

        //创建一条空白的排期任务
        if(!"copy".equals(dtoParam.getType())){
            Task  task=new Task();
            task.setTaskCode(getNewTaskcode());
            task.setProjectCode(sypqProject.getProjectCode());
            task.setTaskType(1);
            task.setStatus(1);
            task.setDeletedFlg("0");
            this.taskMapper.insert(task);
            //复制船模.桨模.附体
            createTaskModel(sypqProject.getProjectCode(),task.getTaskCode());
        }


        try{
            //待处理通知置为已读
            Notice dealNotice = new Notice();
            dealNotice.setBizId(sypqProject.getProjectCode());
            dealNotice.setNoticeTitle("项目审核结果（不通过）");
            noticeService.dealDone(dealNotice);
            //待办通知
            if(res){
                String content = "("+sypqProject.getProjectName()+")项目更新待审核" ;
                Notice notice = new Notice();
                notice.setNoticeType(2);
                notice.setPendingType("项目提交审核通知");
                notice.setNoticeTitle("项目提交审核通知");
                notice.setNoticeContent(content);
                notice.setReceiveUserId(sypqProject.getAuditorid());
                notice.setUrl("/sypqProject");
                notice.setBizId(sypqProject.getProjectCode());
                noticeService.createNotice(notice);
            }
        }catch (Exception e){
            log.error("commitSypqProject: notice error:", e);
        }
        return res;

    }




    @Override
    @Transactional
    public boolean saveAuditSypqProject(WorkflowRecord workflowRecord) {
        String projectcode = workflowRecord.getVoucherId();
        SypqProject sypqProject = baseMapper.selectById(projectcode);
        sypqProject.setApproveStatus(workflowRecord.getStatus());
        this.baseMapper.updateById(sypqProject);
        workflowRecord.setVoucherType("5");
        workflowRecord.setDeletedFlg("0");
        boolean res = workflowRecordService.createWorkflowRecord(workflowRecord);
        if(res){
            try{
                //待处理通知置为已读
                Notice dealNotice = new Notice();
                dealNotice.setBizId(projectcode);
                dealNotice.setNoticeTitle("项目提交审核通知");
                noticeService.dealDone(dealNotice);
                //待办通知
                Notice notice = new Notice();
                String content = "";
                if(4 == workflowRecord.getStatus()){
                    notice.setNoticeType(1);
                    content = "("+sypqProject.getProjectName()+")项目审核已通过" ;
                    notice.setNoticeTitle("项目审核结果（通过）");
                }else if(3 == workflowRecord.getStatus()){
                    notice.setNoticeType(2);
                    notice.setNoticeTitle("项目审核结果（不通过）");
                    notice.setUrl("/sypqProject");
                    notice.setBizId(projectcode);
                    content = "("+sypqProject.getProjectName()+")项目审核未通过(原因：" + workflowRecord.getRemark() + ")，请及时修改" ;
                }
                notice.setPendingType("项目审核结果");
                notice.setNoticeContent(content);
                ProjectManager projectManager = new ProjectManager();
                projectManager.setProjectCode(sypqProject.getProjectCode());
                List<ProjectManager> pmList = projectManagerService.findProjectManagerList(projectManager);
                if(CollectionUtil.isNotEmpty(pmList)){
                    String userIds = pmList.stream().map(ProjectManager::getUserId).collect(Collectors.joining(","));
                    notice.setReceiveUserId(userIds);
                }
                noticeService.createNotice(notice);

            }catch (Exception e){
                log.error("saveAuditSypqProject: notice error:", e);
            }
        }
        return res;
    }

    /**
     * 逻辑删除
     *
     * @param sypqProject    sypqProject
     * @param sypqProjectIds sypqProjectIds
     * @author ganjun
     * @date 2024-11-12 10:58:48
     */
    @Override
    @Transactional
    public boolean deleteSypqProject(SypqProject sypqProject, String sypqProjectIds) {
        boolean result = false;
        User user = (User) getSubject().getPrincipal();
        List<String> list = Arrays.asList(sypqProjectIds.split(StringPool.COMMA));
        sypqProject.setDeletedBy(user.getUserName());
        sypqProject.setDeletedTime(new Date());
        sypqProject.setDeletedFlg(FebsConstant.INVALID);
        int update = this.baseMapper.update(sypqProject,
                                            new LambdaQueryWrapper<SypqProject>().in(SypqProject::getProjectCode,
                                                                                     list));
        if (update > 0) {
            result = true;
        }
        //删除项目经理表
        ProjectManager projectManager = new ProjectManager();
        projectManager.setProjectCode(sypqProjectIds);
        List<ProjectManager> projectManagerList = projectManagerService.findProjectManagerList(projectManager);
        String ids = projectManagerList.stream().map(obj -> obj.getId().toString()).collect(Collectors.joining(","));
        projectManagerService.deleteProjectManager(projectManager, ids);
        return result;
    }

    @Override
    @Transactional
    public boolean  stopSypqProject(String projectCode) {
        SypqProject  sypqProject=baseMapper.selectById(projectCode);
        sypqProject.setStatus(8);
        LambdaQueryWrapper<Task> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Task::getDeletedFlg, 0);
        queryWrapper.eq(Task::getProjectCode, projectCode);
        List<Task>  taskList=this.taskMapper.selectList(queryWrapper);
         for(Task  task:taskList){
             task.setStatus(9);
           this.taskMapper.deleteSchedule(task);
         }
         return   this.updateById(sypqProject);
    }
    /**
     * 物理删除
     *
     * @param sypqProjectIds sypqProjectIds
     * @author ganjun
     * @date 2024-11-12 10:58:48
     */
    @Override
    @Transactional
    public boolean physicallyDeleteSypqProject(String sypqProjectIds) {
        List<String> list = Arrays.asList(sypqProjectIds.split(StringPool.COMMA));
        LambdaQueryWrapper<SypqProject> wapper = new LambdaQueryWrapper<>();
        wapper.in(SypqProject::getProjectCode, list);
        return this.remove(wapper);
    }

    public String getNewProjectCode() {
        String prefix = "PJ" + DateUtil.getDateFormat(new Date(), "yyyyMM");
        String maxSerialNo = baseMapper.getMaxSerialNo(prefix);
        if (StringUtils.isNotEmpty(maxSerialNo)) {
            maxSerialNo = maxSerialNo.substring(8, 12);
            if (maxSerialNo.matches("\\d{4}")) {
                Integer serialno = (Integer.valueOf(maxSerialNo) + 10001);
                return prefix + String.valueOf(serialno).substring(1);
            } else {
                return prefix + "0001";
            }
        } else {
            return prefix + "0001";
        }
    }

    @Override
    public void copymodel(String projectCode,String newProjectcode) {
        Map<String,String>  old2NewMap=new HashMap<>();
        copyShip(projectCode,newProjectcode,old2NewMap);
        copyOars(projectCode,newProjectcode,old2NewMap);
        copyAttach(projectCode,newProjectcode,old2NewMap);
         copyTask(projectCode,newProjectcode,old2NewMap);

    }

    public void copyAttach(String projectCode,String newProjectcode,Map<String,String> old2NewMap) {
        LambdaQueryWrapper<ModelAttach> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ModelAttach::getDeletedFlg, 0);
        queryWrapper.eq(ModelAttach::getProjectCode, projectCode);
        List<ModelAttach> modelAttachList = modelAttachMapper.selectList(queryWrapper);
        if (CollectionUtils.isNotEmpty(modelAttachList)) {
            for (ModelAttach model : modelAttachList) {
                ModelAttach newModel = new ModelAttach();
                BeanUtil.copyProperties(model, newModel);
                newModel.setProjectCode(newProjectcode);
                String dateStr = DateUtil.getDateFormat(new Date(), "yyyyMM");
                Random random = new Random();
                int randomNumber = random.nextInt(10000); // 生成0到9999之间的随机数
                String ftNo = "FT" + dateStr + String.format("%04d", randomNumber);
                newModel.setAttachCode(ftNo);
                newModel.setStatus(1);
                newModel.setStatusName(dictService.findDictLabel("MODEL_ATTACH_STATUS", "1"));
                newModel.setId(UUID.randomUUID().toString().replace("-", ""));
                newModel.setActuallyStartdate(null);
                newModel.setActuallyEnddate(null);
                modelAttachMapper.insert(newModel);
                old2NewMap.put(model.getAttachCode(),newModel.getAttachCode());
            }
        }
    }


    public  void  createTaskModel(String projectCode,String taskCode){
        LambdaQueryWrapper<ModelShip> modelShipWrapper = new LambdaQueryWrapper<>();
        modelShipWrapper.eq(ModelShip::getDeletedFlg, 0);
        modelShipWrapper.eq(ModelShip::getProjectCode, projectCode);
        List<ModelShip> modelShipList = modelShipMapper.selectList(modelShipWrapper);
        taskShipService.physicallyDeleteByTaskcode(taskCode);
        if (CollectionUtils.isNotEmpty(modelShipList)) {
            for (ModelShip model : modelShipList) {
                TaskShip  taskShip=new TaskShip();
                taskShip.setTaskCode(taskCode);
                taskShip.setShipCode(model.getShipCode());
                taskShip.setDeletedFlg("0");
                this.taskShipService.save(taskShip);
            }
        }
        LambdaQueryWrapper<ModelOars> modelOarsWrapper = new LambdaQueryWrapper<>();
        modelOarsWrapper.eq(ModelOars::getDeletedFlg, 0);
        modelOarsWrapper.eq(ModelOars::getProjectCode, projectCode);
        List<ModelOars>  modelOarsList=modelOarsMapper.selectList(modelOarsWrapper);
        taskOarsService.physicallyDeleteByTaskcode(taskCode);
        if (CollectionUtils.isNotEmpty(modelOarsList)) {
            for (ModelOars  model : modelOarsList) {
                TaskOars  taskOars=new TaskOars();
                taskOars.setTaskCode(taskCode);
                taskOars.setOarsCode(model.getOarsCode());
                taskOars.setDeletedFlg("0");
                this.taskOarsService.save(taskOars);
            }
        }

        LambdaQueryWrapper<ModelAttach> modelAttachWrapper = new LambdaQueryWrapper<>();
        modelAttachWrapper.eq(ModelAttach::getDeletedFlg, 0);
        modelAttachWrapper.eq(ModelAttach::getProjectCode, projectCode);
        List<ModelAttach>  modelAttachList=modelAttachMapper.selectList(modelAttachWrapper);
        taskAttachService.physicallyDeleteByTaskcode(taskCode);
        if (CollectionUtils.isNotEmpty(modelAttachList)) {
            for (ModelAttach  model : modelAttachList) {
                TaskAttach  taskAttach=new TaskAttach();
                taskAttach.setTaskCode(taskCode);
                taskAttach.setAttachCode(model.getAttachCode());
                taskAttach.setDeletedFlg("0");
                this.taskAttachService.save(taskAttach);
            }
        }
    }



    public  void  copyShip(String projectCode,String  newProjectCode,Map<String,String> old2NewMap) {
        LambdaQueryWrapper<ModelShip> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ModelShip::getDeletedFlg, 0);
        queryWrapper.eq(ModelShip::getProjectCode, projectCode);
        List<ModelShip> modelShipList = modelShipMapper.selectList(queryWrapper);
        if (CollectionUtils.isNotEmpty(modelShipList)) {
            for (ModelShip model : modelShipList) {
                ModelShip newModel = new ModelShip();
                BeanUtil.copyProperties(model, newModel);
                newModel.setProjectCode(newProjectCode);
                newModel.setStatus(1);
                newModel.setSource(2);
                newModel.setStatusName(dictService.findDictLabel("MODEL_SHIP_PROCESS_STATUS", "1"));
                Random random = new Random();
                int randomNumber = random.nextInt(10000); // 生成0到9999之间的随机数
                String dateStr = DateUtil.getDateFormat(new Date(), "yyyyMM");
                String bmNo = "BM" + dateStr + String.format("%04d", randomNumber);
                newModel.setShipCode(bmNo);
                newModel.setActuallyStartdate(null);
                newModel.setActuallyEnddate(null);
                newModel.setId(UUID.randomUUID().toString().replace("-", ""));
                modelShipMapper.insert(newModel);
                old2NewMap.put(model.getShipCode(),newModel.getShipCode());
            }
        }
    }



        public  void  copyOars(String projectCode,String newProjectcode,Map<String,String> old2NewMap){
            LambdaQueryWrapper<ModelOars> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ModelOars::getDeletedFlg, 0);
            queryWrapper.eq(ModelOars::getProjectCode, projectCode);
            List<ModelOars> modelOarsList = modelOarsMapper.selectList(queryWrapper);
             if(CollectionUtils.isNotEmpty(modelOarsList)) {
                 for (ModelOars model : modelOarsList) {
                     ModelOars newModel = new ModelOars();
                     BeanUtil.copyProperties(model, newModel);
                     newModel.setProjectCode(newProjectcode);
                     String dateStr = DateUtil.getDateFormat(new Date(), "yyyyMM");
                     Random random = new Random();
                     int randomNumber = random.nextInt(10000); // 生成0到9999之间的随机数
                     String jmNo = "JM" + dateStr + String.format("%04d", randomNumber);
                     newModel.setOarsCode(jmNo);
                     newModel.setStatus(1);
                     newModel.setStatusName(dictService.findDictLabel("MODEL_OARS_STATUS", "1"));
                     newModel.setId(UUID.randomUUID().toString().replace("-", ""));
                     newModel.setActuallyStartdate(null);
                     newModel.setActuallyEnddate(null);
                     modelOarsMapper.insert(newModel);
                     old2NewMap.put(model.getOarsCode(),newModel.getOarsCode());
                 }
             }
        }


    public  void  copyTask(String projectCode,String  newProjectcode,Map<String,String> old2NewMap){
        LambdaQueryWrapper<Task> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Task::getDeletedFlg, 0);
        queryWrapper.eq(Task::getProjectCode, projectCode);
        List<Task> taskList = taskMapper.selectList(queryWrapper);
        if(CollectionUtils.isNotEmpty(taskList)) {
            for (Task task : taskList) {
                Task newTask = new Task();
                BeanUtil.copyProperties(task, newTask);
                newTask.setStatus(1);
                newTask.setTaskCode(getNewTaskcode());
                newTask.setProjectCode(newProjectcode);
                newTask.setPlanStartdate(null);
                newTask.setPlanStarttime(null);
                newTask.setPlanEnddate(null);
                newTask.setPlanEndtime(null);
                newTask.setActuallyStartdate(null);
                newTask.setActuallyEnddate(null);
                newTask.setPauseDate(null);
                newTask.setPauseTime(null);
                newTask.setPauseReason(null);
                taskMapper.insert(newTask);
                 //复制船模
                LambdaQueryWrapper<TaskShip> taskShipWrapper = new LambdaQueryWrapper<>();
                taskShipWrapper.eq(TaskShip::getDeletedFlg, 0);
                taskShipWrapper.eq(TaskShip::getTaskCode, task.getTaskCode());
                List<TaskShip> taskShipList=this.taskShipService.list(taskShipWrapper);
                for(TaskShip  taskShip:taskShipList){
                    TaskShip newShip=new TaskShip();
                    BeanUtil.copyProperties(taskShip,newShip );
                    newShip.setTaskCode(newTask.getTaskCode());
                    newShip.setDeletedFlg("0");
                    newShip.setShipCode(old2NewMap.get(taskShip.getShipCode()));
                    newShip.setId(null);
                    this.taskShipService.save(newShip);
                }

                LambdaQueryWrapper<TaskOars> taskOarsWrapper = new LambdaQueryWrapper<>();
                taskOarsWrapper.eq(TaskOars::getDeletedFlg, 0);
                taskOarsWrapper.eq(TaskOars::getTaskCode, task.getTaskCode());
                List<TaskOars> taskOarsList=this.taskOarsService.list(taskOarsWrapper);
                for(TaskOars  taskOars:taskOarsList){
                    TaskOars newOars=new TaskOars();
                    BeanUtil.copyProperties(taskOars,newOars );
                    newOars.setTaskCode(newTask.getTaskCode());
                    newOars.setDeletedFlg("0");
                    newOars.setId(null);
                    newOars.setOarsCode(old2NewMap.get(taskOars.getOarsCode()));
                    this.taskOarsService.save(newOars);
                }

                LambdaQueryWrapper<TaskAttach> taskAttachWrapper = new LambdaQueryWrapper<>();
                taskAttachWrapper.eq(TaskAttach::getDeletedFlg, 0);
                taskAttachWrapper.eq(TaskAttach::getTaskCode, task.getTaskCode());
                List<TaskAttach> taskAttachList=this.taskAttachService.list(taskAttachWrapper);
                for(TaskAttach  taskAttach:taskAttachList){
                    TaskAttach newAttach=new TaskAttach();
                    BeanUtil.copyProperties(taskAttach,newAttach );
                    newAttach.setTaskCode(newTask.getTaskCode());
                    newAttach.setDeletedFlg("0");
                    newAttach.setId(null);
                    newAttach.setAttachCode(old2NewMap.get(taskAttach.getAttachCode()));
                    this.taskAttachService.save(newAttach);
                }
            }
        }
    }

    private String  getNewTaskcode(){
        String prefix= "TK" + DateUtil.getDateFormat(new Date(), "yyyyMM");
        String maxSerialNo= taskMapper.getMaxSerialNo(prefix);
        if(StringUtils.isNotEmpty(maxSerialNo)){
            maxSerialNo=maxSerialNo.substring(8,12);
            if(maxSerialNo.matches("\\d{4}")){
                Integer   serialno=(Integer.valueOf(maxSerialNo)+10001);
                return  prefix+String.valueOf(serialno).substring(1);
            }else {
                return prefix+"0001";
            }
        }else {
            return   prefix+"0001";
        }
    }

   public   String  checkProject(SypqProject project){
        SypqProject dto1=new SypqProject();
        dto1.setProjectCode(project.getProjectCode());
        List<SypqProject>  list=findSypqProjectList(dto1);
        StringBuffer sb=new StringBuffer();
        if(list.size()>0){
            sb.append("项目编码已存在!");
        }
       SypqProject   dto2=new SypqProject();
        dto2.setProjectName(project.getProjectName());
       List<SypqProject>  list2=findSypqProjectList(dto2);
       if(list2.size()>0){
           if(sb.length()>0){
               sb.append(";");
           }
           sb.append("项目名称已存在!");
       }
        return  sb.toString();
    }

}
